/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:flutter/material.dart';
import 'dart:math';

import 'avoid_area_manager.dart';

class GamePage extends StatefulWidget {
  const GamePage({super.key});

  @override
  State<GamePage> createState() => _GamePageState();
}

class _GamePageState extends State<GamePage> {
  ///鸟类图片列表
  final List<String> birdImages = [
    'assets/bird_red.png',
    'assets/bird_blue.png',
    'assets/bird_green.png',
    'assets/bird_white.png',
    'assets/bird_purple.png',
    'assets/bird_yellow.png',
  ];

  late AvoidAreaManager areaManager;
  var avoidAreaState = AvoidAreaState();
  late ValueChanged<AvoidAreaState> listener;

  @override
  void initState() {
    super.initState();
    areaManager = AvoidAreaManager();
    listener = (value) {
      Future.microtask(() {
        setState(() {
          avoidAreaState = value;
        });
      });
    };
    areaManager.addListener(listener);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    areaManager.updateMediaQuery(context);
  }

  @override
  void dispose() {
    super.dispose();
    areaManager.removeListener(listener);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Image.asset(
            'assets/background.png',
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),
          Container(
            margin: avoidAreaState.padding,
            padding: const EdgeInsets.all(10),
            child: Column(
              children: [
                Row(
                  children: [
                    createSizedBox(CutoutPosition.topLeft,
                        widthOffset: getWidthOffset(true)),
                    Expanded(child: _buildTop()),
                    createSizedBox(CutoutPosition.topRight,
                        widthOffset: getWidthOffset(false)),
                  ],
                ),
                Expanded(
                  child: Row(
                    children: [
                      createSizedBox(CutoutPosition.left,
                          widthOffset: getWidthOffset(true)),
                      Expanded(child: _buildCenter()),
                      createSizedBox(CutoutPosition.right,
                          widthOffset: getWidthOffset(false)),
                    ],
                  ),
                ),
                Row(
                  children: [
                    createSizedBox(CutoutPosition.bottomLeft,
                        widthOffset: getWidthOffset(true)),
                    Expanded(child: _buildBottom()),
                    createSizedBox(CutoutPosition.bottomRight,
                        widthOffset: getWidthOffset(false)),
                  ],
                ),
                createSizedBox(CutoutPosition.bottomCenter,
                    heightOffset: getHeightOffset(false)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///顶部控件
  Widget _buildTop() {
    return areaManager.isTablet()
        ? Row(
      children: [
              Image.asset('assets/goal.png'),
              Expanded(
                  child: Center(
                child: Column(
                  children: [
                    createSizedBox(CutoutPosition.topCenter,
                        heightOffset: getHeightOffset(true)),
                    Image.asset('assets/scoring.png')
                  ],
                ),
              )),
              Image.asset('assets/steps.png'),
            ],
          )
        : areaManager.isLandscape()
            ? Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Image.asset('assets/goal.png'),
                      const SizedBox(width: 10),
                      Image.asset('assets/steps.png'),
                    ],
                  ),
                  Row(
                    children: [
                      Image.asset('assets/suspended.png'),
                      const SizedBox(width: 10),
                      Image.asset('assets/shopping.png'),
                      const SizedBox(width: 10),
                      Image.asset('assets/props.png'),
                    ],
                  ),
                ],
              )
            : Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Image.asset('assets/goal.png'),
                  Image.asset('assets/steps.png'),
                ],
              );
  }

  ///底部控件
  Widget _buildBottom() {
    return areaManager.isTablet()
        ? Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Image.asset('assets/suspended.png'),
              Row(
                children: [
                  Image.asset('assets/shopping.png'),
                  const SizedBox(
                    width: 10,
                    height: 5,
                  ),
                  Image.asset('assets/props.png'),
                ],
              )
            ],
          )
        : areaManager.isLandscape()
            ? const SizedBox()
            : Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Image.asset('assets/suspended.png'),
                  Image.asset('assets/shopping.png'),
                  Image.asset('assets/props.png'),
                ],
              );
  }

  ///中间控件
  Widget _buildCenter() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 10),
      child: LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          const itemSize = 80.0;
          final crossAxisCount = (constraints.maxWidth / itemSize).floor();
          final mainAxisCount = (constraints.maxHeight / itemSize).floor() + 1;

          final List<List<String>> gameGrid =
              List.generate(mainAxisCount, (row) {
            return List.generate(crossAxisCount, (col) {
              final randomIndex = Random().nextInt(birdImages.length);
              return birdImages[randomIndex];
            });
          });

          return GridView.builder(
            padding: EdgeInsets.zero,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: crossAxisCount,
              childAspectRatio: 1.0,
            ),
            itemCount: gameGrid.length * gameGrid[0].length,
            itemBuilder: (BuildContext context, int index) {
              final row = index ~/ gameGrid[0].length;
              final col = index % gameGrid[0].length;
              final tileImage = gameGrid[row][col];
              return Container(
                width: itemSize - 20,
                height: itemSize - 20,
                padding: const EdgeInsets.all(5.0),
                margin: const EdgeInsets.all(5.0),
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/background_box.png'),
                    fit: BoxFit.cover,
                  ),
                ),
                child: Image.asset(tileImage),
              );
            },
          );
        },
      ),
    );
  }

  Widget createSizedBox(CutoutPosition cutoutPosition,
      {double widthOffset = 0, double heightOffset = 0}) {
    return cutoutPosition == avoidAreaState.cutoutPosition
        ? SizedBox(
            width: avoidAreaState.rect.width + widthOffset,
            height: avoidAreaState.rect.height + heightOffset,
          )
        : const SizedBox(
            width: 0,
            height: 0,
          );
  }

  double getWidthOffset(bool isLeft) {
    if (isLeft) {
      return avoidAreaState.rect.left < 0 ? 0 : avoidAreaState.rect.left;
    }
    double offsetRight =
        (areaManager.getScreenWidth() - avoidAreaState.rect.right);
    if (offsetRight < 0) {
      offsetRight = 0;
    }
    return offsetRight;
  }

  double getHeightOffset(bool isTop) {
    if (isTop) {
      return avoidAreaState.rect.top;
    }
    double offsetBottom =
        (areaManager.getScreenHeight() - avoidAreaState.rect.bottom);
    if (offsetBottom < 0) {
      offsetBottom = 0;
    }
    return offsetBottom;
  }
}
